//
//  LHPicCollectionView.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/24.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit
import SDWebImage

private let itemMargin : CGFloat = 5
private let picWH = CGFloat(Int(SCREENW - MARGIN * 2 - 2 * itemMargin) / 3)

class LHPicCollectionView: UICollectionView {

	let itemID = "PICEITEM"
	var picArr : [LHPicM]? {

		didSet {

//			let sizeO = self.getSizeToCell(picArr!.count)

			self.snp_updateConstraints { (make) -> Void in
				make.size.equalTo(getSizeToCell(picArr!.count))
//                make.width.equalTo(getSizeToCell(picArr!.count).width)
//                  make.height.equalTo(getSizeToCell(picArr!.count).height)
			}

			self.reloadData()
		}
	}

	override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
		super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())

		self.registerClass(LHPicCell.self, forCellWithReuseIdentifier: itemID)

		dataSource = self
		delegate = self

		self.scrollsToTop = false
//        self.collectionViewLayout
		setupUI()
	}

	private func setupUI() {

		let layout = collectionViewLayout as! UICollectionViewFlowLayout

		layout.minimumLineSpacing = itemMargin
		layout.minimumInteritemSpacing = itemMargin
		layout.sectionInset = UIEdgeInsetsZero
		layout.itemSize = CGSize(width: picWH, height: picWH)
	}

	func getSizeToCell(count: Int) -> CGSize {

//        print(count)
		let col = count == 4 ? 2 : (count > 3 ? 3 : count)
		let row = (count + 2) / 3

		let witde = CGFloat(col) * picWH + CGFloat(col - 1) * itemMargin
		let hight = CGFloat(row) * picWH + CGFloat(row - 1) * itemMargin

//        print("\(witde)\n\(hight)")
		return CGSizeMake(witde, hight)
	}

	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
}

extension LHPicCollectionView : UICollectionViewDataSource {

	func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

		return picArr?.count ?? 0
	}

	func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

		let cell = dequeueReusableCellWithReuseIdentifier(itemID, forIndexPath: indexPath) as! LHPicCell

		cell.picM = picArr![indexPath.item]

		return cell
	}
}

extension LHPicCollectionView : UICollectionViewDelegate {

	func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

		let picM = picArr![indexPath.item]
		guard let imageO = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picM.thumbnail_pic) else {

			return
		}

//		print(picArr![indexPath.item])
		let window = UIApplication.sharedApplication().keyWindow!

		let barVC = window.rootViewController as! LHTabBarController

		for i in 0..<picArr!.count {

			let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as! LHPicCell
			let picM = picArr![i]
			picM.rect = cell.convertRect(cell.imageV.frame, toView: window)
		}

		let bigColl = LHBigPicCollection()
		bigColl.showsHorizontalScrollIndicator = false

		barVC.view.addSubview(bigColl)

		bigColl.frame = window.bounds

		bigColl.backgroundColor = UIColor(white: 0, alpha: 0)

//		UIView.animateWithDuration(0.25) { () -> Void in
//            bigColl.backgroundColor = UIColor(white: 20/255, alpha: 0.9)
//		}

//		let bigV = LHBigPicView()

//		bigV.frame = window.bounds

//		bigV.numLbl.text = "\(indexPath.item+1)/\(picArr!.count)"
//
//		window.addSubview(bigV)
//
//		bigV.backgroundColor = UIColor.blackColor()
//
//		bigV.alpha = 0
//
//		UIView.animateWithDuration(0.25) { () -> Void in
//			bigV.alpha = 0.9
//		}

//		let cell = collectionView.cellForItemAtIndexPath(indexPath) as! LHPicCell
//		let cen : CGPoint = cell.imageV.center

		let imageW = UIImageView()

		window.addSubview(imageW)

//		print(picM.thumbnail_pic)

		imageW.image = imageO

		imageW.frame = picM.rect!
//       ://ww3.sinaimg.cn/bmiddle/90c94367gw1f0cxzvd1mpj20qo0zkq6n.jpg

//       tp://ww3.sinaimg.cn/thumbnail/90c94367gw1f0cxzvd1mpj20qo0zkq6n.jpg
//		var str : String = picM.thumbnail_pic!
//
//		if (str.rangeOfString("thumbnail") != nil) {
//
//			str = str.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
//		}
//
//		imageW.sd_setImageWithURL(NSURL(string: str), placeholderImage: imageO)

//		print("\(cell.convertRect(cell.frame, toView: window))----\(cell.imageV.frame)")
//        window.addSubview(cell.imageV)
		UIView.animateWithDuration(0.25, animations: { () -> Void in

//			imageW.transform = CGAffineTransformMakeScale(SCREENW / imageO.size.width, SCREENW / imageO.size.width)
			bigColl.backgroundColor = UIColor(white: 0, alpha: 0.9)
			imageW.frame.size.width = SCREENW
			imageW.frame.size.height = SCREENW * imageO.size.height / imageO.size.width
			imageW.center = CGPointMake(SCREENW * 0.5, SCREENH * 0.5)
		}) { (_) -> Void in

//            bigColl.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.None)
			bigColl.picArr = self.picArr
			bigColl.indexP = indexPath

			imageW.removeFromSuperview()
		}
//
//			UIView.animateWithDuration(5, animations: { () -> Void in
//
////				imageW.transform = CGAffineTransformMakeScale(0, 0)
//				imageW.frame.size.width = imageO.size.width
//				imageW.frame.size.height = imageO.size.height
//				imageW.frame = cell.convertRect(cell.imageV.frame, toView: window)
//			}) { (_) -> Void in
//
//				imageW.removeFromSuperview()
//			}
//		})
//
//		bigV.finishBack = {
//
//			UIView.animateWithDuration(0.5, animations: { () -> Void in
//
//				// imageW.transform = CGAffineTransformMakeScale(0, 0)
//				imageW.frame.size.width = imageO.size.width
//				imageW.frame.size.height = imageO.size.height
//				imageW.frame = cell.convertRect(cell.imageV.frame, toView: window)
//				bigV.alpha = 0
//			}) { (_) -> Void in
//
//				imageW.removeFromSuperview()
//				bigV.removeFromSuperview()
//			}
//		}
	}
}
